import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import {
  Clip,
  Timeline,
  Track,
  Effect,
  Transition,
  EffectType,
  TransitionType,
} from '@/types/video';

// 临时类型定义 - 与Redux Toolkit兼容的Effect类型
interface EffectState {
  id: string;
  type: EffectType;
  name: string;
  parameters: Record<string, any>;
  startTime: number;
  duration: number;
  enabled: boolean;
}

// 临时类型定义 - 与Redux Toolkit兼容的Transition类型
interface TransitionState {
  id: string;
  type: TransitionType;
  name: string;
  duration: number;
  position: 'start' | 'end';
  parameters: Record<string, any>;
}

interface TimelineState {
  // 当前时间线
  currentTimeline: Timeline | null;

  // 当前编辑的剪辑
  clips: Clip[];

  // 播放状态
  isPlaying: boolean;
  currentTime: number;
  playheadPosition: number;

  // 缩放级别
  zoomLevel: number;

  // 当前选中的剪辑
  selectedClipId: string | null;

  // 总时长
  duration: number;

  // 轨道信息
  tracks: Track[];

  // 播放状态
  playbackRate: number;
}

const initialState: TimelineState = {
  currentTimeline: null,
  clips: [],
  isPlaying: false,
  currentTime: 0,
  playheadPosition: 0,
  zoomLevel: 1,
  selectedClipId: null,
  duration: 0,
  tracks: [],
  playbackRate: 1.0,
};

const timelineSlice = createSlice({
  name: 'timeline',
  initialState,
  reducers: {
    // 设置当前时间线
    setCurrentTimeline: (state, action: PayloadAction<Timeline>) => {
      state.currentTimeline = action.payload;
      state.clips = action.payload.tracks.flatMap(track => track.clips);
      state.duration = action.payload.duration;
    },

    // 添加视频剪辑
    addVideoClip: (state, action: PayloadAction<Clip>) => {
      const clip = action.payload;
      state.clips.push(clip);

      // 更新总时长
      const clipEndTime = clip.trackStartTime + clip.duration;
      if (clipEndTime > state.duration) {
        state.duration = clipEndTime;
      }
    },

    // 移除剪辑
    removeClip: (state, action: PayloadAction<string>) => {
      const clipId = action.payload;
      state.clips = state.clips.filter(clip => clip.id !== clipId);

      // 重新计算总时长
      if (state.clips.length === 0) {
        state.duration = 0;
      } else {
        state.duration = Math.max(...state.clips.map(clip => clip.trackStartTime + clip.duration));
      }
    },

    // 分割剪辑
    splitClip: (state, action: PayloadAction<{ clipId: string; splitTime: number }>) => {
      const { clipId, splitTime } = action.payload;
      const clipIndex = state.clips.findIndex(clip => clip.id === clipId);

      if (clipIndex !== -1) {
        const clip = state.clips[clipIndex];
        const relativeSplitTime = splitTime - clip.trackStartTime;

        if (relativeSplitTime > 0 && relativeSplitTime < clip.duration) {
          // 创建第一个剪辑片段
          const firstClip: Clip = {
            ...clip,
            id: Math.random().toString(36).substr(2, 9),
            duration: relativeSplitTime,
            endTime: clip.trackStartTime + relativeSplitTime,
          };

          // 创建第二个剪辑片段
          const secondClip: Clip = {
            ...clip,
            id: Math.random().toString(36).substr(2, 9),
            trackStartTime: clip.trackStartTime + relativeSplitTime,
            trimStart: clip.trimStart + relativeSplitTime,
            duration: clip.duration - relativeSplitTime,
            endTime: clip.endTime,
          };

          // 替换原剪辑
          state.clips.splice(clipIndex, 1, firstClip, secondClip);
        }
      }
    },

    // 更新剪辑位置
    updateClipPosition: (
      state,
      action: PayloadAction<{ clipId: string; trackStartTime: number }>
    ) => {
      const { clipId, trackStartTime } = action.payload;
      const clip = state.clips.find(clip => clip.id === clipId);

      if (clip) {
        clip.trackStartTime = trackStartTime;
        clip.endTime = trackStartTime + clip.duration;

        // 更新总时长
        const maxEndTime = Math.max(...state.clips.map(c => c.endTime));
        state.duration = maxEndTime;
      }
    },

    // 设置当前时间
    setCurrentTime: (state, action: PayloadAction<number>) => {
      state.currentTime = Math.max(0, Math.min(action.payload, state.duration));
      state.playheadPosition = state.currentTime;
    },

    // 设置播放头位置
    setPlayheadPosition: (state, action: PayloadAction<number>) => {
      state.playheadPosition = Math.max(0, Math.min(action.payload, state.duration));
    },

    // 设置缩放级别
    setZoomLevel: (state, action: PayloadAction<number>) => {
      state.zoomLevel = action.payload;
    },

    // 播放/暂停
    togglePlayback: state => {
      state.isPlaying = !state.isPlaying;
    },

    // 设置播放状态
    setPlaybackState: (state, action: PayloadAction<boolean>) => {
      state.isPlaying = action.payload;
    },

    // 设置播放速率
    setPlaybackRate: (state, action: PayloadAction<number>) => {
      state.playbackRate = action.payload;
    },

    // 选择剪辑
    selectClip: (state, action: PayloadAction<string | null>) => {
      state.selectedClipId = action.payload;
    },

    // 清空时间线
    clearTimeline: state => {
      state.clips = [];
      state.currentTime = 0;
      state.playheadPosition = 0;
      state.duration = 0;
      state.selectedClipId = null;
    },

    // 添加轨道
    addTrack: (state, action: PayloadAction<Track>) => {
      state.tracks.push(action.payload);
    },

    // 移除轨道
    removeTrack: (state, action: PayloadAction<string>) => {
      state.tracks = state.tracks.filter(track => track.id !== action.payload);
    },

    // 添加特效到剪辑
    addEffect: (state, action: PayloadAction<{ clipId: string; effect: EffectState }>) => {
      const { clipId, effect } = action.payload;
      const clip = state.clips.find(clip => clip.id === clipId);

      if (clip) {
        if (!clip.effects) {
          clip.effects = [];
        }
        clip.effects.push(effect as Effect);
      }
    },

    // 更新特效
    updateEffect: (
      state,
      action: PayloadAction<{ clipId: string; effectId: string; updates: Partial<EffectState> }>
    ) => {
      const { clipId, effectId, updates } = action.payload;
      const clip = state.clips.find(clip => clip.id === clipId);

      if (clip && clip.effects) {
        const effect = clip.effects.find(effect => effect.id === effectId);
        if (effect) {
          Object.assign(effect, updates);
        }
      }
    },

    // 移除特效
    removeEffect: (state, action: PayloadAction<{ clipId: string; effectId: string }>) => {
      const { clipId, effectId } = action.payload;
      const clip = state.clips.find(clip => clip.id === clipId);

      if (clip && clip.effects) {
        clip.effects = clip.effects.filter(effect => effect.id !== effectId);
      }
    },

    // 添加转场到剪辑
    addTransition: (
      state,
      action: PayloadAction<{ clipId: string; transition: TransitionState }>
    ) => {
      const { clipId, transition } = action.payload;
      const clip = state.clips.find(clip => clip.id === clipId);

      if (clip) {
        if (!clip.transitions) {
          clip.transitions = [];
        }
        clip.transitions.push(transition as Transition);
      }
    },

    // 更新转场
    updateTransition: (
      state,
      action: PayloadAction<{
        clipId: string;
        transitionId: string;
        updates: Partial<TransitionState>;
      }>
    ) => {
      const { clipId, transitionId, updates } = action.payload;
      const clip = state.clips.find(clip => clip.id === clipId);

      if (clip && clip.transitions) {
        const transition = clip.transitions.find(transition => transition.id === transitionId);
        if (transition) {
          Object.assign(transition, updates);
        }
      }
    },

    // 移除转场
    removeTransition: (state, action: PayloadAction<{ clipId: string; transitionId: string }>) => {
      const { clipId, transitionId } = action.payload;
      const clip = state.clips.find(clip => clip.id === clipId);

      if (clip && clip.transitions) {
        clip.transitions = clip.transitions.filter(transition => transition.id !== transitionId);
      }
    },
  },
});

export const {
  setCurrentTimeline,
  addVideoClip,
  removeClip,
  splitClip,
  updateClipPosition,
  setCurrentTime,
  setPlayheadPosition,
  setZoomLevel,
  togglePlayback,
  setPlaybackState,
  setPlaybackRate,
  selectClip,
  clearTimeline,
  addTrack,
  removeTrack,
  addEffect,
  updateEffect,
  removeEffect,
  addTransition,
  updateTransition,
  removeTransition,
} = timelineSlice.actions;

export default timelineSlice.reducer;
